/**
 * Created by lumix on 2015/4/22.
 */
var express = require('express');
var router = express.Router();
var Promise = require('promise');
var interceptor = require('../../../utils/interceptor');
var wechatRest = require('../../../utils/wechatRest');
var comm = require('../../../utils/commonUtils');
var lingService = require('../service/12LingService_s01e01.js');
var logger = require('log4js').getLogger('12Ling_s01e01');
var commonUtils = require('./../../../utils/commonUtils');
var SETTING_ID = 35;

router.all('*', interceptor.verifyUserAuth);

//起始页
router.get('/startup', interceptor.verifyJsTicket, function (req, res, next) {
    var fans = req.session.fans;
    if (!(fans && fans.openId)) {
        res.state(404).end();
        return;
    }
    var likeId = comm.get36SystemTo10System(req.query.instance);
    var data = {hostname: req.hostname, own: true, f_instance: '0'};

    lingService.getLikeById(likeId).then(function (f_like) {
        if (!!f_like && f_like.sponsorOpenid != fans.openId) {
            //从别人分享的链接进到自己主页
            data.own = false;
            data.f_instance = comm.get10SystemTo36System(f_like.id);
        }
    }).then(function () {
        return lingService.getLikeByParams({settingId: SETTING_ID, sponsorOpenid: fans.openId});
    }).then(function (like) {
        if (like) {
            if (comm.isBlank(like.name) || comm.isBlank(like.remarks)) {
                like.name = fans.nickname;
                like.remarks = fans.headImgUrl;
                return lingService.updateLike(like).then(function () {
                    return Promise.resolve(like);
                });
            } else {
                return Promise.resolve(like);
            }
        } else {
            //新建一个
            var _like = {
                settingId: SETTING_ID, sponsorOpenid: fans.openId,
                collect: 0, remarks: fans.headImgUrl, name: fans.nickname, createTime: new Date()
            };
            return lingService.saveLike(_like);
        }
    }).then(function (like) {
        var _result = {like: like};
        var _parameter = {
            settingId: SETTING_ID,
            actorOpenid: fans.openId
        }
        if (data.own) {
            _parameter.likeId = like.id;
        } else {
            _parameter.likeId = comm.get36SystemTo10System(data.f_instance)
        }
        return lingService.getCollectors(_parameter).then(function (collectors) {
            _result.collectors = collectors;
            return Promise.resolve(_result);
        });
    }).then(function (result) {
        var like = result.like;
        var collectors = result.collectors;
        data.wechatSign = wechatRest.wechatSign(req);
        data.instance = comm.get10SystemTo36System(like.id);
        data.done = false;
        data.collect = like.collect;

        var today = new RegExp(new Date().format('yyyy-MM-dd'));
        collectors.forEach(function (item) {
            if (today.test(item.createTimeStr)) {
                data.done = true;//当天已完成
            }
        });

        logger.debug(data);
        res.render('biz/12ling/views/s01e01/startup', data);

    }, function (err) {
        logger.error('startup error' + err);
        res.state(500).end();
    });
});

//游戏页面
router.get('/game', interceptor.verifyJsTicket, function (req, res, next) {
    var fans = req.session.fans;
    if (!(fans && fans.openId)) {
        res.state(404).end();
        return;
    }
    var likeId = comm.get36SystemTo10System(req.query.instance);
    var f_likeId = comm.get36SystemTo10System(req.query.f_instance);
    var data = {hostname: req.hostname, instance: req.query.instance, f_instance: req.query.f_instance};
    logger.info("------------------------------------game---------------------------------------------");
    logger.info("----------------------------------instance:--" + req.query.instance + "---------------------------------------------");
    logger.info("----------------------------------f_instance:--" + req.query.f_instance + "---------------------------------------------");
    logger.info("----------------------------------f_likeId:--" + f_likeId + "---------------------------------------------");
    lingService.getLikeById(likeId).then(function (like) {
        if (like) {
            return Promise.resolve(like);
        } else {//根据openid查找
            return Promise.resolve(null);
        }
    }).then(function (like) {
        if (like) {
            var _result = {like: like};
            var _parameter = {
                settingId: SETTING_ID,
                actorOpenid: fans.openId
            }
            logger.info(f_likeId == 0);
            logger.info(f_likeId == '0');
            logger.info(f_likeId);
            if (likeId == f_likeId || f_likeId == 0 || f_likeId == '0') {
                data.own = true;
                _parameter.likeId = like.id;
            } else {
                data.own = false;
                _parameter.likeId = comm.get36SystemTo10System(data.f_instance)
            }
            return lingService.getCollectors(_parameter).then(function (collectors) {
                _result.collectors = collectors;
                return Promise.resolve(_result);
            });
        } else {
            return Promise.resolve(null);
        }
    }).then(function (result) {
        if (result && result.like) {
            var like = result.like;
            var collectors = result.collectors;
            data.wechatSign = wechatRest.wechatSign(req);
            data.instance = comm.get10SystemTo36System(like.id);
            data.f_instance = req.query.f_instance;
            data.done = false;
            data.collect = like.collect;

            var today = new RegExp(new Date().format('yyyy-MM-dd'));
            collectors.forEach(function (item) {
                if (today.test(item.createTimeStr)) {
                    data.done = true;//当天已完成
                }
            });

            logger.debug(data);
            res.render('biz/12ling/views/s01e01/game', data);
        } else {
            logger.info("------------------------------------跳转到主页---------------------------------------------");
            logger.info("-----------------------------------/biz/12ling_s01e01/startup---------------------------------------------");
            res.redirect('/biz/12ling_s01e01/startup');
        }
    }, function (err) {
        logger.error('startup error' + err);
        res.state(500).end();
    });
});

//自己为自己加分的场合
router.post('/addMyScore', function (req, res) {
    var fans = req.session.fans;
    if (!(fans && fans.openId)) {
        res.json({'success': false, 'msg': 'no authority'});
        return;
    }

    var score = parseInt(req.body.score);
    if (typeof score != 'number') {
        logger.error("incorrect parameters|score");
        res.json({'success': false, 'msg': 'incorrect parameters'});
        return;
    }

    logger.info("----------------------------------------addMyScore----------------------------------");
    logger.info("req.body.score" + req.body.score);

    var message = "加分操作成功！";
    Promise.all([
        lingService.getLikeByParams({settingId: SETTING_ID, sponsorOpenid: fans.openId}),
        lingService.getCollectors({settingId: SETTING_ID, sponsorOpenid: fans.openId, actorOpenid: fans.openId})
    ]).then(function (r) {
        var like = r[0];
        var collectors = r[1];

        var addFlag = true;
        var today = new RegExp(new Date().format('yyyy-MM-dd'));
        collectors.forEach(function (item) {
            if (today.test(item.createTimeStr)) {
                addFlag = false;
                message = "今天已经加过分了，请明天再来！";
            }
        });

        if (addFlag) {
            return lingService.addMyScore(like, score).then(function (r) {
                if (!r) {
                    message = "对不起，发生系统错误！";
                }
                return Promise.resolve(r);
            });
        } else {
            return Promise.resolve(null);
        }
    }).then(function (result) {
        logger.info("----------------------------------------addMyScore---result-------------------------------");
        logger.info(result);
        if (result) {
            res.json({success: true, msg: message});
        } else {
            res.json({success: false, msg: message});
        }
    }, function (err) {
        logger.error('myScore error:', err);
        res.json({success: false, msg: err});
    })
});

//别人为自己加分接口
router.post('/addScore', function (req, res) {
    var fans = req.session.fans;
    if (!(fans && fans.openId)) {
        res.json({'success': false, 'msg': 'no authority'});
        return;
    }
    var score = parseInt(req.body.score);
    if (typeof score != 'number') {
        logger.error("incorrect parameters|score");
        res.json({'success': false, 'msg': 'incorrect parameters|score'});
        return;
    }

    var f_likeId = comm.get36SystemTo10System(req.body.f_instance);
    logger.info("----------------------------------------addScore----------------------------------");
    logger.info("req.body.f_instance" + req.body.f_instance);
    logger.info("req.body.score" + req.body.score);

    var message = "加分操作成功！";
    lingService.getLikeById(f_likeId).then(function (f_like) {
        var result = {addFlag: true};
        if (f_like) {
            result.f_like = f_like;
            if (f_like.sponsorOpenid == fans.openId) {
                message = "帮朋友加分的场合，接口调用错误！";
                result.addFlag = false;
                return Promise.resolve(result);
            } else {
                var params = {settingId: SETTING_ID, likeId: f_like.id, actorOpenid: fans.openId};
                return lingService.getCollectors(params).then(function (collectors) {
                    var today = new RegExp(new Date().format('yyyy-MM-dd'));
                    collectors.forEach(function (item) {
                        if (today.test(item.createTimeStr)) {
                            result.addFlag = false;
                            message = "今天已经加过分了，请明天再来！";
                        }
                    });
                    return Promise.resolve(result);
                });
            }
        } else {
            message = "系统无法找到源用户，加分失败！";
            result.addFlag = false;
            return Promise.resolve(result);
        }
    }).then(function (result) {
        if (result.addFlag) {
            var params = {settingId: SETTING_ID, sponsorOpenid: fans.openId};
            return lingService.getLikeByParams(params).then(function (myLike) {
                if (myLike) {
                    return Promise.resolve(myLike);
                } else {
                    params.remarks = fans.headImgUrl;
                    params.name = fans.nickname;
                    params.collect = 0;
                    params.createTime = new Date();
                    return lingService.saveLike(params);
                }
            }).then(function (myLike) {
                result.myLike = myLike;
                return Promise.resolve(result);
            });
        } else {
            return Promise.resolve(result);
        }
    }).then(function (result) {
        if (result.addFlag) {
            return lingService.addScore(result.f_like, result.myLike, score).then(function (r) {
                message = "系统内部发生错误，加分失败！";
                return Promise.resolve(r);
            });
        } else {
            return Promise.resolve(null);
        }
    }).then(function (result) {
        logger.info("----------------------------------------addScore--result--------------------------------");
        logger.info(result);
        if (result) {
            res.json({success: true, msg: message});
        } else {
            res.json({success: false, msg: message});
        }
    }, function (err) {
        logger.error('score error:', err);
        res.json({success: false, msg: err});
    })
});

//我的酒庄
router.post('/myChateau', function (req, res) {
    var fans = req.session.fans;
    if (!(fans && fans.openId)) {
        res.json({'success': false, 'msg': 'no authority'});
        return;
    }

    lingService.getMyChateau(SETTING_ID, fans.openId).then(function (data) {
        res.json({'success': true, 'msg': 'success', data: data});
    }, function (err) {
        logger.error('myPrize error:', err);
        res.json({'success': false, 'msg': err});
    })
});

//奖品兑换
router.post('/cashPrize', function (req, res) {
    var fans = req.session.fans;
    if (!(fans && fans.openId)) {
        res.json({'success': false, 'msg': 'no authority'});
        return;
    }
    var record = {settingId: SETTING_ID};
    //// 0：实物  1：虚拟
    //var prizeType = req.body.prizeType;
    //if (comm.isNumber(prizeType) && prizeType == 0) {
    //    record.name = req.body.name;
    //    record.phone = req.body.phone;
    //    record.address = req.body.address;
    //    if (comm.isBlank(record.name) || !comm.isNumber(record.phone) || comm.isBlank(record.address)) {
    //        res.json({'success': false, 'msg': 'incorrect parameters'});
    //        return;
    //    }
    //}

    var message = "";
    var record = {settingId: SETTING_ID};
    record.settingId = SETTING_ID;
    record.openid = fans.openId;
    record.createTime = new Date();

    if (comm.isNumber(req.body.level)) {
        record.score = req.body.level;
    } else {
        res.json({'success': false, 'msg': 'incorrect parameters'});
        return;
    }

    var subscribe = false;
    wechatRest.getFans(fans.openId, req.session.account.accessToken).then(function (fans) {
        if (fans && !commonUtils.isBlank(fans.subscribe)) {
            subscribe = true;
            logger.info("已关注");
            return Promise.resolve(true);
        } else {
            logger.info("未关注");
            subscribe = false;
            message = "用户未关注";
            return Promise.resolve(false);
        }
    }).then(function (_subscribe) {
        if (_subscribe) {
            return lingService.getLikeByParams({
                settingId: SETTING_ID,
                sponsorOpenid: fans.openId
            }).then(function (like) {
                if (like) {
                    return lingService.cashPrize(like, record).then(function (r) {
                        message = r.msg;
                        return Promise.resolve(r);
                    });
                } else {
                    message = "没有查找到该like信息！";
                    return Promise.resolve(null);
                }
            });
        } else {
            return Promise.resolve(null);
        }

    }).then(function (result) {
        if (result && result.cashFlag) {
            res.json({'success': true, 'msg': message, subscribe: subscribe, data: {record: result.record}});
        } else {
            res.json({'success': false, 'msg': message, subscribe: subscribe});
        }
    }, function (err) {
        logger.error('cashPrize error:', err);
        res.json({'success': false, 'msg': err});
    });
});

//获取朋友帮忙列表
router.post('/getFriends', function (req, res) {
    var fans = req.session.fans;
    if (!(fans && fans.openId)) {
        res.json({'success': false, 'msg': 'no authority'});
        return;
    }

    var likeId = comm.get36SystemTo10System(req.body.instance);
    logger.info("----------------------------------------getFriends----------------------------------");
    logger.info("req.body.instance" + req.body.instance);

    lingService.getLikeById(likeId).then(function (like) {
        if (like && like.id) {
            return lingService.getFriendCollects(like);
        } else {
            return Promise.resolve(null);
        }
    }).then(function (result) {
        logger.info("----------------------------------------getFriends--result--------------------------------");
        logger.info(result);
        if (result) {
            res.json({success: true, msg: 'success', data: result});
        } else {
            res.json({success: false, msg: 'fail'});
        }
    }, function (err) {
        logger.error('score error:', err);
        res.json({success: false, msg: err});
    })
});

module.exports = router;